import { Directive, ElementRef, Input, HostListener, OnChanges } from '@angular/core';
import { Router } from '@angular/router';


@Directive({
  selector:'[paging]'
})

export class PagingDirective implements OnChanges{
  @Input('paging') paging:any;

  constructor(
    private router:Router,
    private elementRef:ElementRef
  ){
  }


  //参数变化时重新生成分页按钮
  ngOnChanges(){
    let name = this.paging.name;
    let params = this.paging.params;
    let pageMax = Number(params.pageMax);
    let pageNumber = Number(params.pageNumber);
    let prev = pageNumber-1;
    let next = pageNumber+1;
    let htmlText = '';
    //let urlParams = this.getUrlParams(params);

    params = JSON.stringify(params);

    if(prev < 1){
      prev = 1;
    }

    if(next > pageMax){
      next = pageMax;
    }

    htmlText += '<a name="'+name+'" pageNumber="'+prev+'" params='+params+'>上一页</a>';

    for(let i=0; i<pageMax; i++){
      let num = i+1;

      if(pageNumber === num){
        htmlText += '<a class="on" name="'+name+'" pageNumber="'+num+'" params='+params+'>'+num+'</a>';
      }else{
        htmlText += '<a name="'+name+'" pageNumber="'+num+'" params='+params+'>'+num+'</a>';
      }
    }

    htmlText += '<a name="'+name+'" pageNumber="'+next+'" params='+params+'>下一页</a>';

    this.elementRef.nativeElement.innerHTML = htmlText;
  }



  //绑定点击事件
  @HostListener('click',['$event'])
  onClick(event:Event){
    let nodeName = event.srcElement.nodeName;

    if(nodeName === 'A'){
      let attributes = event.srcElement.attributes;
      let name = attributes['name'].value;
      let pageNumber = attributes['pageNumber'].value;
      let params = JSON.parse(attributes['params'].value);

      params = Object.assign(params,{pageNumber:pageNumber});

      this.router.navigate([name],{queryParams:params});
    }
  }



  // private getUrlParams(params:Object):any{
  //   let urlParams = '';
  //   let notParams = ['pageNumber','pageSize','pageMax'];

  //   for(let key in params){
  //     if(notParams.indexOf(key) === -1){
  //       urlParams += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
  //     }
  //   }

  //   return urlParams;
  // }


}